<template>
  <VPage class="app-container">
    <VTable v-if="isRefresh" ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <div class="w-full">
          <el-tabs v-model="activeName" class="pl-4 pr-4" @tab-change="handleChange">
            <el-tab-pane :label="item.label" :name="item.name" v-for="(item, index) in tabList"
              :key="index"></el-tab-pane>
          </el-tabs>
        </div>
        <template v-if="activeName == 0">
          <VGroup>
            <el-select style="max-width: 100px" v-model="form.personRange.type" placeholder="请选择">
              <el-option v-for="item in personOptions" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
            <select-personnel class="w-50" v-model="form.personRange.value"></select-personnel>
          </VGroup>
          <el-select v-model="form.order_status" placeholder="状态" multiple collapse-tags>
            <el-option v-for="item in options['waremanage.inventoryCountOrder']?.[0].inventoryCountOrderStatus"
              :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </template>
        <el-select v-model="form.verify_status" placeholder="审核状态" multiple collapse-tags>
          <el-option v-for="item in options['waremanage.inventoryCountOrder']?.[0].inventoryCountOrderVerify"
            :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="form.type" placeholder="盘点类型" multiple collapse-tags>
          <el-option v-for="item in options['waremanage.inventoryCountOrder']?.[0].inventoryCountOrderType"
            :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <template v-if="activeName == 0">
          <el-select class="w-30" v-model="form.is_print" placeholder="打印状态">
            <el-option v-for="item in options['waremanage.inventoryCountOrder']?.[0].inventoryCountOrderIsPrint"
              :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </template>
        <VGroup>
          <el-select class="selectClass" v-model="form.timeRange.type" style="max-width: 120px">
            <el-option v-for="item in timeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-date-picker v-model="form.timeRange.value" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime()"
            style="max-width: 300px" />
        </VGroup>
        <multiInput v-model="form.inventory_count_order_no" placeholder="盘点单" class="w-50"></multiInput>
        <multiInput v-model="form.sku" placeholder="SKU" class="w-50"></multiInput>
      </template>
      <template #toolbar_btns>
        <template v-if="activeName == 0">
          <el-button type="primary" @click="open('add')"><svg-icon class="text-white mr-1" icon-class="add"/>新增</el-button>
          <el-button @click="handleAudit">审核</el-button>
          <el-button @click="handleCancel">取消</el-button>
          <el-button class="ml-auto" @click="handleExport"><svg-icon icon-class="import" />导出</el-button>
          <el-button  @click="handleImport"><svg-icon icon-class="download01" />导入</el-button>
        </template>
      </template>
    </VTable>
    <ComModal ref="ComModalRef" @query="query"></ComModal>
    <importFile ref="importRef" type="location" :api="importLocation" @query="query"></importFile>
    <derived-center ref="DerivedCenterRef"></derived-center>
  </VPage>
</template>
<script setup name="InventoryInventory-count-order" lang="jsx">
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick, ref, reactive, toRefs } from 'vue'
import { getEnums } from '@/api/public'
import { queryInventoryCountList, printDetailInventoryCount, verifyInventoryCount, cancelInventoryCount, confirmInventoryCount } from './api'
import ComModal from './components/ComModal.vue'
import importFile from '@/components/importFile';
import multiInput from '@/components/multiInput'

const timeOption = [
  { label: "创建时间", value: "create_time" },
  { label: "审核时间", value: "verify_time" },
]

const personOptions = [
  { label: "盘点人", value: "count_user_id" },
  { label: "审核人", value: "verify_user_id" },
  { label: "创建人", value: "create_user_id" },
]

const activeName = ref(0)
const tabList = [
  {
    label: '库内盘点',
    name: 0
  },
  {
    label: '盘点明细',
    name: 1
  },
]

const tableRef = ref()
const tableOptins = reactive({
  rowConfig: { height: 60 },
  formConfig: {
    data: {
      personRange: { type: 'count_user_id', value: [], range: true },
      timeRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [],
  proxyConfig: {
    seq: true,
    props: {
      result: 'data',
      total: 'total',
    },
    ajax: {
      query: async ({ page, form }) => {
        const requestFun = activeName.value == 0 ? queryInventoryCountList : printDetailInventoryCount
        const res = await requestFun({ ...form, ...page })
        return new Promise(function (resolve) {
          resolve({
            data: res.data,
            total: res.total
          })
        })
      }
    }
  }
})
const query = () => {
  tableRef.value.query()
}

const initColumns = (type) => {
  if (type == 0) {
    tableOptins.columns = [
      { type: 'checkbox', width: "40" },
      {
        field: 'inventory_count_order_no', title: '盘点单', width: 180
      },
      {
        field: 'warehouse_name', title: '仓库', width: 120
      },
      {
        field: 'type_cn', title: '盘点类型', width: 120
      },
      {
        field: 'order_status_cn', title: '盘点状态', width: 120
      },
      {
        field: 'sku_count', title: 'SKU数量', width: 100
      },
      {
        field: 'sku_num', title: 'SKU件数', width: 100
      },
      {
        field: 'is_diff', title: '盘点是否差异', width: 120
      },
      {
        field: 'stock_true_rate', title: '库存准确率（库存）', width: 160
      },
      {
        field: 'stock_amount_true_rate', title: '库存准确率（金额）', width: 160
      },
      {
        field: 'count_user', title: '盘点人', width: 160
      },
      {
        field: 'create_user', title: '创建人', width: 160
      },
      {
        field: 'create_time', title: '创建日期', width: 180
      },
      {
        field: 'is_print', title: '打印', width: 120
      },
      {
        field: 'verify_status_cn', title: '审核状态', width: 120
      },
      {
        field: 'verify_user', title: '审核人', width: 160
      },
      {
        field: 'verify_time', title: '审核时间', width: 180
      },
      {
        title: '操作', width: "100", fixed: "right", slots: {
          default: ({ row }) => {
            return <div class="table-option">
              <div>
                <el-link type="primary" underline={false} class="mr-2" onClick={() => handlePrint(row)}>打印</el-link>
                {row.order_status == 1 && <el-link type="primary" underline={false} class="mr-2" onClick={() => handleConfirm(row.id)}>确认</el-link>}
              </div>
            </div >
          }
        }
      }
    ]
  } else if (type == 1) {
    tableOptins.columns = [
      {
        type: "seq", title: '序号',width: 80
      },
      {
        field: 'sku', title: 'SKU'
      },
      {
        field: 'location_code', title: '货位'
      },
      {
        field: 'location_num', title: '货位数量'
      },
      {
        field: 'count_num', title: '盘点数量'
      },
      {
        field: 'diff_num', title: '盈亏数量'
      },
      {
        field: 'count_result', title: '盘点结果'
      },
      {
        field: 'sku_cn_title', title: '产品名称',width: 300
      },
    ]
  }
}
initColumns(0)
const isRefresh = ref(true)
const handleChange = (val) => {
  initColumns(activeName.value)
  isRefresh.value = false
  nextTick(() => {
    isRefresh.value = true
  })
  console.log(tableOptins)
  refresh()
}



const data = reactive({
  options: []
})
const { options } = toRefs(data)

// 获取枚举类
const fetchOption = async () => {
  getEnums({
    version: "v1", "name": [
      "waremanage.inventoryCountOrder"
    ]
  }).then(res => {
    options.value = res.data
  })
}
provide('options', options)
fetchOption()

const ComModalRef = ref()
const open = (type, id) => {
  ComModalRef.value.open(type, id)
}

// 审核
const handleAudit = () => {
  const records = getSelectRow().map(i => {
    return i.id
  })
  if (records.length == 0) {
    ElMessage.error('请先选择行')
    return
  }
  ElMessageBox.confirm('是否审核当前勾选项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    verifyInventoryCount({ ids: records })
      .then((res) => {
        query()
        ElMessage.success(res.message)
      })
  })
}

// 取消
const handleCancel = () => {
  const records = getSelectRow().map(i => {
    return i.id
  })
  if (records.length == 0) {
    ElMessage.error('请先选择行')
    return
  }
  ElMessageBox.confirm('是否取消当前勾选项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cancelInventoryCount({ ids: records })
      .then((res) => {
        query()
        ElMessage.success(res.message)
      })
  })
}

const handleConfirm = (id) => {
  ElMessageBox.confirm('是否确认当前项?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    confirmInventoryCount({ ids: [id] })
      .then((res) => {
        query()
        ElMessage.success(res.message)
      })
  })

}

const handlePrint = () => {
  ElMessage.error('暂时不写')
}

// 导入
const importRef = ref()
const handleImport = () => {
  // nextTick(() => {
  //   importRef.value.open()
  // })
}

const DerivedCenterRef = ref()
const handleExport = (val) => {
  let condition = tableRef.value.getQueryForm()
  DerivedCenterRef.value.open({
    id: 45,
    tag_name: 'wms',
    condition
  })
}
//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords()
}

</script>
<style scoped>
:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}
</style>